<template>
  <div class="fishing-spots-page">
    <!-- Header - 固定头部 -->
    <div class="header">
      <div class="header-controls">
        <!-- 城市选择器 - 参考yukoume-container实现 -->
        <div class="city-selector-container">
          <button class="action-btn city-selector"  @click="selectCity">
            <span class="btn-icon">📍</span>
            <span>{{ selectedCityName || '选择城市' }}</span>
            <span class="btn-arrow">▼</span>
          </button>
          <div v-if="showCitySelector" class="city-selector-panel">
            <div class="city-panel-header">
              <span>选择城市</span>
              <button @click="showCitySelector = false" class="close-btn">×</button>
            </div>
            <div class="city-search">
              <input 
                v-model="citySearchQuery" 
                type="text" 
                placeholder="搜索城市..."
                class="city-search-input"
              />
            </div>
            <div class="city-list">
              <div 
                v-for="city in filteredCities" 
                :key="city.cityCode" 
                @click="selectCityItem(city)"
                class="city-item"
                :class="{ active: selectedCity === city.cityCode }">
                {{ city.city }}
              </div>
              <div v-if="filteredCities.length === 0" class="no-cities">
                暂无城市数据
              </div>
            </div>
          </div>
        </div>
        
        <!-- 简化筛选按钮 -->
        <div class="filter-buttons">
          <button 
            class="filter-btn" 
            :class="{ active: isFree !== null }"
            @click="toggleFilter('isFree')">
            {{ isFree === null ? '全部(收费/免费)' : (isFree ? '免费' : '收费') }}
          </button>
          <button 
            class="filter-btn" 
            :class="{ active: isPrivate !== null }"
            @click="toggleFilter('isPrivate')">
            {{ isPrivate === null ? '全部(秘密/公开)' : (isPrivate? '私人' : '公共') }}
          </button>
          <button 
            class="filter-btn" 
            :class="{ active: isForbidden !== null }"
            @click="toggleFilter('isForbidden')">
            {{ isForbidden === null ? '全部(禁钓/可钓)' : (isForbidden? '禁钓' : '可钓') }}
          </button>
          <button class="reset-btn" @click="resetFilters">重置</button>
        </div>
        
        <!-- 添加钓点按钮 - 移到最右边 -->
        <button class="search-btn" @click="showAddSpotModal = true">
          <span class="btn-icon">➕</span>
          添加钓点
        </button>
      </div>
    </div>

    <!-- 数据表格 - 滚动分页 -->
    <div class="table-container" @scroll="handleScroll">
      <table class="data-table">
        <thead>
          <tr>
            <th>ID</th>
            <th>钓点名称</th>
            <th>城市</th>
            <th>经纬度</th>
            <th>类型</th>
            <th>等级</th>
            <th>钓点类型</th>
            <th>鱼种</th>
            <th>免费</th>
            <th>私人</th>
            <th>禁钓</th>
            <th>停车</th>
            <th>距离</th>
            <th>创建时间</th>
            <th>更新时间</th>
          </tr>
        </thead>
        <tbody>
          <tr 
            v-for="spot in spots" 
            :key="spot.id" 
            class="table-row clickable-row"
            @click="goToSpotDetail(spot.id)">
            <td>{{ spot.id }}</td>
            <td class="spot-name">{{ spot.name }}</td>
            <td>{{ spot.city }}</td>
            <td class="coordinates">
              {{ spot.longitude.toFixed(6) }}, {{ spot.latitude.toFixed(6) }}
            </td>
            <td>{{ spot.waterType.name }}</td>
            <td>
              <span class="level-badge" :class="`level-${spot.lvl}`">
                {{ spot.lvl.name }}
              </span>
            </td>
            <td class="json-data">
              <pre>{{ toListLabels(spot.jsonSpotTypes) }}</pre>
            </td>
            <td class="json-data">
              <pre>{{ toListLabels(spot.jsonFishTypes) }}</pre>
            </td>
            <td>
              <span :class="['status-badge', spot.isFree ? 'free' : 'paid']">
                {{ spot.isFree ? '是' : '否' }}
              </span>
            </td>
            <td>
              <span :class="['status-badge', spot.isPrivate ? 'private' : 'public']">
                {{ spot.isPrivate ? '是' : '否' }}
              </span>
            </td>
            <td>
              <span :class="['status-badge', spot.isForbidden ? 'forbidden' : 'allowed']">
                {{ spot.isForbidden ? '是' : '否' }}
              </span>
            </td>
            <td>
              <span :class="['status-badge', spot.isParkingConvenient ? 'convenient' : 'inconvenient']">
                {{ spot.isParkingConvenient ? '方便' : '不便' }}
              </span>
            </td>
            <td>{{ spot.distance.name }}</td>
            <td>{{ formatDate(spot.createdAt) }}</td>
            <td>{{ formatDate(spot.updatedAt) }}</td>
          </tr>
        </tbody>
      </table>
      
      <!-- 空状态 -->
      <div v-if="spots.length === 0 && !loading" class="empty-state">
        <div class="empty-icon">🎣</div>
        <p>暂无钓点数据</p>
      </div>
      
      <!-- 加载更多 -->
      <div v-if="loading" class="loading-more">
        <div class="loading-spinner"></div>
        <p>加载更多...</p>
      </div>
    </div>
    <!-- 加载状态 -->
    <div v-if="loading" class="loading">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
  </div>
  
  <!-- 添加钓点表单组件 -->
  <AddSpotForm 
    :is-visible="showAddSpotModal"
    :cities="cities.map(city => ({ id: parseInt(city.cityCode), name: city.city }))"
    @close="handleAddSpotClose"
    @submit="handleAddSpotSubmit"
  />
</template>

<script setup lang="ts">
import { ref, onMounted, watch, computed, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { invoke } from '@tauri-apps/api/core'
import AddSpotForm from '../AddSpotForm.vue'
interface CommonType {
  id: number
  name: string
}

interface FishingSpot {
  id: number
  cityCode: string
  city: string
  longitude: number
  latitude: number
  name: string
  isFree: boolean
  isPrivate: boolean
  isForbidden: boolean
  waterType: CommonType
  lvl: CommonType
  jsonSpotTypes: Array<CommonType>
  jsonFishTypes: Array<CommonType>
  isParkingConvenient: boolean
  distance: CommonType
  createdAt: string
  updatedAt: string
}

interface Location {
  longitude: number
  latitude: number
}

interface LinePoint extends Location {}

interface AddSpotForm {
  id: string
  circleId: string
  name: string
  location: Location
  line: LinePoint[]
  pics: string[]
  spotTypes: string[]
  fishTypes: string[]
  isFree: number
  parkingEasy: number
  lvl: string
  distance: string
  secret: number
  waterType: string
  description: string
}

// 路由
const router = useRouter()

// 状态管理
const spots = ref<FishingSpot[]>([])
const loading = ref(false)
const currentPage = ref(1)
const pageSize = ref(30)
const totalPages = ref(1)
const totalRecords = ref(0)
const hasMore = ref(true)

// 添加钓点表单相关状态
const showAddSpotModal = ref(false)

// 筛选条件
const selectedCity = ref('')
  const selectedCityName = ref('')
  const showCitySelector = ref(false)
  const citySearchQuery = ref('')
  const searchQuery = ref('')
  const cities = ref<{ cityCode: string; city: string }[]>([])
  
  const isFree = ref<boolean | null>(null)
  const isPrivate = ref<boolean | null>(null)
  const isForbidden = ref<boolean | null>(null)
  const isLoadingCities = ref(false)

// 城市选择相关方法
  const filteredCities = computed(() => {
    if (!citySearchQuery.value) return cities.value
    return cities.value.filter(city => 
      city.city.includes(citySearchQuery.value) || 
      city.cityCode.includes(citySearchQuery.value)
    )
  })
  const selectCity = () => {
  showCitySelector.value = !showCitySelector.value
  if (showCitySelector.value) {
    fetchCities()
  }
}


// 获取城市列表 - 调用后端API
const fetchCities = async () => {
  if(cities.value.length > 0) return;
  isLoadingCities.value = true
  try {
    const response = await invoke('get_circle_cities')

    // 处理API响应格式
    if (response && Array.isArray((response as any).data)) {
      cities.value = (response as any).data as Array<{ cityCode: string; city: string }>
    } else if (Array.isArray(response)) {
      cities.value = response as Array<{ cityCode: string; city: string }>
    } else {
      console.warn('城市API响应格式未知:', response)
      cities.value = []
    }
  } catch (err) {
    console.error('获取城市列表失败:', err)
    // API调用失败时显示空列表，不显示默认城市
    cities.value = []
  } finally {
    isLoadingCities.value = false
  }
}
  const selectCityItem = (city: { cityCode: string; city: string }) => {
    selectedCity.value = city.cityCode
    selectedCityName.value = city.city
    showCitySelector.value = false
    citySearchQuery.value = ''
    
    // 保存到本地存储
    localStorage.setItem('selectedCity', JSON.stringify({
      city: city.city,
      cityCode: city.cityCode
    }))
    
    currentPage.value = 1
    spots.value = []
    hasMore.value = true
    loadSpots()
  }

  // 监听筛选条件变化
  watch([selectedCity, isFree, isPrivate, isForbidden], () => {
    currentPage.value = 1
    spots.value = [] // 清空现有数据
    hasMore.value = true
    loadSpots()
  })

// 切换筛选条件 - 简化版
  const toggleFilter = (filterType: string) => {
    switch (filterType) {
      case 'isFree':
        if (isFree.value === null) isFree.value = true
        else if (isFree.value === true) isFree.value = false
        else isFree.value = null
        break
      case 'isPrivate':
        if (isPrivate.value === null) isPrivate.value = true
        else if (isPrivate.value) isPrivate.value = false
        else isPrivate.value = null
        break
      case 'isForbidden':
        if (isForbidden.value === null) isForbidden.value = true
        else if (isForbidden.value) isForbidden.value = false
        else isForbidden.value = null
        break
    }
    currentPage.value = 1
    spots.value = [] // 清空数据，重新加载
    loadSpots()
  }
const hanlderSpotSearch = (event: CustomEvent) => {
   const customEvent = event as CustomEvent
  const { query } = customEvent.detail || {}
  searchQuery.value = query.trim();
  loadSpots()
}

// 加载钓点数据 - 滚动加载，使用正确的API格式
const loadSpots = async () => {
  if (currentPage.value === 1) {
    loading.value = true
  }
  
  try {
    const params = new URLSearchParams()
    
    if (selectedCity.value) params.append('cityCode', selectedCity.value)
    if (isFree.value !== null) params.append('isFree', isFree.value.toString())
    if (isPrivate.value !== null) params.append('isPrivate', isPrivate.value.toString())
    if (isForbidden.value !== null) params.append('isForbidden', isForbidden.value.toString())
    if (searchQuery.value) params.append('query', searchQuery.value)
    
    params.append('pageNum', currentPage.value.toString())
    params.append('pageSize', pageSize.value.toString())

    const response = await invoke('get_spots', { query: params.toString() })
    
    // 定义响应类型
    interface ApiResponse {
      data?: {
        records?: FishingSpot[];
        total?: number;
        pages?: number;
      }
    }
    
    if (response && typeof response === 'object' && 'data' in response) {
      const typedResponse = response as ApiResponse
      const data = typedResponse.data || {}
      const newSpots = data.records || []
      
      if (currentPage.value === 1) {
        spots.value = newSpots
      } else {
        spots.value.push(...newSpots)
      }
      
      totalRecords.value = data.total || 0
      totalPages.value = data.pages || 1
      hasMore.value = currentPage.value < totalPages.value
    } else {
      if (currentPage.value === 1) {
        spots.value = []
        totalPages.value = 1
        totalRecords.value = 0
      }
      hasMore.value = false
    }
  } catch (error) {
    console.error('加载钓点失败:', error)
    if (currentPage.value === 1) {
      spots.value = []
    }
  } finally {
    loading.value = false
  }
}

// 重置筛选条件
  const resetFilters = () => {
    selectedCity.value = ''
    isFree.value = null
    isPrivate.value = null
    isForbidden.value = null
    currentPage.value = 1
    spots.value = [] // 清空数据
    loadSpots()
  }

// 滚动加载
  const handleScroll = (event: { target: any }) => {
    const container = event.target
    const { scrollTop, scrollHeight, clientHeight } = container
    
    // 当滚动到底部附近时加载更多
    if (scrollHeight - scrollTop - clientHeight < 100 && !loading.value && hasMore.value) {
      currentPage.value++
      loadSpots()
    }
  }

// 转换fishTypes为JSON格式并显示名称
const toListLabels = (types: Array<CommonType>) => {
  if (!types) return ''
  return types.map(item => {
      return  item.name
  }).join(',')
}



// 格式化日期
const formatDate = (dateString: string) => {
  if (!dateString) return ''
  return new Date(dateString).toLocaleString('zh-CN')
}

// 跳转到钓点详情页
const goToSpotDetail = (spotId: number) => {
  router.push({
    name: 'SpotDetail',
    params: { id: spotId }
  })
}

// 处理添加钓点表单提交
const handleAddSpotSubmit = async (formData: any) => {
  try {
    // 准备提交数据
    const submitData = {
      id: formData.spotId,
      circleId: formData.circleId,
      name: formData.name,
      location: {
        longitude: parseFloat(formData.longitude),
        latitude: parseFloat(formData.latitude)
      },
      line: formData.linePointsJson ? JSON.parse(formData.linePointsJson) : [],
      pics: formData.imageUrl ? [formData.imageUrl] : [],
      spotTypes: formData.spotTypes,
      fishTypes: formData.fishTypes,
      isFree: formData.price === 'free' ? 1 : 0,
      parkingEasy: 0, // Default value
      lvl: formData.lvls,
      distance: formData.distance,
      secret: formData.price === 'private' ? 1 : 0,
      waterType: formData.waterType,
      description: '', // Default value
      city: formData.city
    }    
    
    // 调用后端API添加钓点
    const response = await invoke('add_spot', { spot: submitData })
    
    // 处理响应
    const result = response as any
    if (result && result.code === 200) {
      alert('添加钓点成功！')
      showAddSpotModal.value = false
      
      // 重新加载钓点列表
      currentPage.value = 1
      spots.value = []
      loadSpots()
    } else {
      alert(`添加失败: ${result?.msg || '未知错误'}`)
    }
  } catch (error) {
    console.error('添加钓点失败:', error)
    alert(`添加失败: ${error instanceof Error ? error.message : '网络错误'}`)
  }
}

// 处理添加钓点模态框关闭
const handleAddSpotClose = () => {
  showAddSpotModal.value = false
}

// 初始化
  onMounted(() => {
    // 从本地存储加载选择的城市
      window.addEventListener('global-search', hanlderSpotSearch as EventListener)
    const savedCity = localStorage.getItem('selectedCity')
    if (savedCity) {
      try {
        const cityData = JSON.parse(savedCity)
        selectedCityName.value = cityData.city
        selectedCity.value = cityData.cityCode
      } catch (error) {
        console.warn('从本地存储加载城市失败:', error)
      }
    }
    loadSpots()
  })

  onUnmounted(() => {
    window.removeEventListener('global-search', hanlderSpotSearch as EventListener)
  })
</script>

<style scoped>
.fishing-spots-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--bg-primary);
  color: var(--text-primary);
}

.header {
  position: sticky;
  top: 0;
  z-index: 100;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background-color: var(--bg-header);
  border-bottom: 1px solid var(--border);
  box-shadow: var(--shadow-card);
}

.header h2 {
  margin: 0;
  color: var(--accent-primary);
  font-size: 24px;
}

.header-controls {
  display: flex;
  gap: 15px;
  align-items: center;
}

/* 城市选择器样式 - 参考yukoume-container */
.city-selector-container {
  position: relative;
}

.action-btn {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 16px;
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
  border: 1px solid var(--border);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  min-width: 80px;
}

.action-btn:hover {
  background-color: var(--bg-card);
  border-color: var(--border-hover);
}

.btn-icon {
  font-size: 14px;
}

.btn-arrow {
  font-size: 10px;
  opacity: 0.7;
}

.city-selector-panel {
  position: absolute;
  top: calc(100% + 8px);
  left: 0;
  width: 200px;
  background: var(--bg-card);
  border: 1px solid var(--border);
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  z-index: 1001;
  max-height: 300px;
  overflow-y: auto;
}

.city-panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border-bottom: 1px solid var(--border);
  font-weight: 600;
  color: var(--text-primary);
}

.close-btn {
  background: none;
  border: none;
  color: var(--text-secondary);
  font-size: 18px;
  cursor: pointer;
  padding: 0;
  width: 20px;
  height: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-btn:hover {
  color: var(--text-primary);
}

.city-search {
  padding: 12px;
  border-bottom: 1px solid var(--border);
}

.city-search-input {
  width: 100%;
  padding: 8px 12px;
  background: var(--bg-input);
  border: 1px solid var(--border);
  border-radius: 4px;
  color: var(--text-primary);
  font-size: 14px;
  outline: none;
}

.city-search-input:focus {
  border-color: var(--accent-primary);
}

.city-search-input::placeholder {
  color: var(--text-secondary);
}

.city-list {
  padding: 4px 0;
}

.city-item {
  padding: 10px 12px;
  cursor: pointer;
  color: var(--text-primary);
  font-size: 14px;
  transition: background-color 0.2s;
}

.city-item:hover {
  background-color: var(--bg-tertiary);
}

.city-item.active {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
}

.no-cities {
  padding: 20px;
  text-align: center;
  color: var(--text-secondary);
  font-size: 14px;
}

.filter-buttons {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.filter-btn {
  padding: 8px 16px;
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
  border: 1px solid var(--border);
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
  font-size: 14px;
  min-width: 80px;
}

.filter-btn:hover {
  background-color: var(--bg-card);
  border-color: var(--border-hover);
}

.filter-btn.active {
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border-color: var(--accent-primary);
}

.search-area {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
  padding: 15px;
  background-color: var(--bg-secondary);
  border-radius: 8px;
}

.search-input {
  flex: 1;
  padding: 10px;
  background-color: var(--bg-input);
  color: var(--text-primary);
  border: 1px solid var(--border);
  border-radius: 4px;
}

.search-btn, .reset-btn {
  padding: 10px 20px;
  background-color: var(--accent-primary);
  color: var(--text-inverse);
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-weight: bold;
  transition: all 0.3s ease;
}

.search-btn:hover, .reset-btn:hover {
  background-color: var(--accent-primary-hover);
}

.reset-btn {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
}

.reset-btn:hover {
  background-color: var(--bg-card);
}

.table-container {
  flex: 1;
  background-color: var(--bg-secondary);
  margin: 20px 20px 40px 20px;
  border-radius: 8px;
  box-shadow: var(--shadow-card);
  overflow-y: auto;
  overflow-x: auto;
  min-height: 400px;
  padding-bottom: 20px;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
  font-size: 14px;
}

.data-table th {
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
  padding: 12px 8px;
  text-align: left;
  font-weight: bold;
  border-bottom: 2px solid var(--border);
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: var(--shadow-hover);
}

.data-table td {
  padding: 10px 8px;
  border-bottom: 1px solid var(--border);
}

.table-row:hover {
  background-color: var(--bg-tertiary);
}

.clickable-row {
  cursor: pointer;
  transition: background-color 0.2s ease;
}

.clickable-row:hover {
  background-color: var(--bg-card);
}

.spot-name {
  color: var(--text-primary);
  font-weight: bold;
}

.coordinates {
  font-family: monospace;
  font-size: 12px;
}

.level-badge {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
  font-weight: bold;
}

.level-A { background-color: var(--accent-danger); color: var(--text-inverse); }
.level-B { background-color: var(--accent-warning); color: var(--text-inverse); }
.level-C { background-color: var(--accent-info); color: var(--text-inverse); }
.level-D { background-color: var(--accent-success); color: var(--text-inverse); }

.fish-types {
  font-size: 12px;
  color: var(--text-secondary);
}

.json-data {
  font-size: 11px;
  color: var(--text-secondary);
  max-width: 200px;
  overflow-x: auto;
}

.json-data pre {
  margin: 0;
  font-family: 'Consolas', 'Monaco', monospace;
  white-space: pre-wrap;
  word-break: break-all;
}

.status-badge {
  padding: 2px 6px;
  border-radius: 3px;
  font-size: 11px;
  font-weight: bold;
}

.free { background-color: var(--accent-success); color: var(--text-inverse); }
.paid { background-color: var(--accent-danger); color: var(--text-inverse); }
.private { background-color: var(--accent-warning); color: var(--text-inverse); }
.public { background-color: var(--accent-success); color: var(--text-inverse); }
.forbidden { background-color: var(--accent-danger); color: var(--text-inverse); }
.allowed { background-color: var(--accent-success); color: var(--text-inverse); }
.convenient { background-color: var(--accent-success); color: var(--text-inverse); }
.inconvenient { background-color: var(--bg-disabled); color: var(--text-inverse); }

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 15px;
  margin-top: 20px;
}

.page-btn {
  padding: 8px 16px;
  background-color: var(--bg-tertiary);
  color: var(--text-primary);
  border: 1px solid var(--border);
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.page-btn:hover:not(:disabled) {
  background-color: var(--bg-card);
}

.page-btn:disabled {
  background-color: var(--bg-disabled);
  color: var(--text-disabled);
  cursor: not-allowed;
}

.page-info {
  color: var(--text-primary);
  font-size: 14px;
}

.empty-state {
  text-align: center;
  padding: 60px 20px;
  color: var(--text-secondary);
}

.empty-icon {
  font-size: 48px;
  margin-bottom: 10px;
}

.loading {
  text-align: center;
  padding: 40px;
  color: var(--accent-primary);
}

.loading-more {
  text-align: center;
  padding: 20px;
  color: var(--text-secondary);
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid var(--border);
  border-top: 4px solid var(--accent-primary);
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin: 0 auto 10px;
}

.loading-more .loading-spinner {
  width: 20px;
  height: 20px;
  border-width: 2px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}


</style>